<?php

namespace app\api\controller\cart;

use app\BaseController;
use think\facade\Validate;

use app\common\model\User\User as UserModel;
use app\common\model\Product\Product as ProductModel;
use app\common\model\Product\Type as TypeModel;
use app\common\model\Product\Vip as VipModel;
use app\common\model\Cart as CartModel;


class Cart extends BaseController
{
    public function initialize()
    {
        parent::initialize();

        $this->UserModel = new UserModel();
        $this->TypeModel = new TypeModel();
        $this->ProductModel = new ProductModel();
        $this->VipModel = new VipModel();
        $this->CartModel = new CartModel();
    }

    // 购物车列表
    public function list()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);

            $cartids = $this->request->param('cartids', '');

            $ispromptly = $this->request->param('ispromptly', '');

            $cartid = explode(',', $cartids) ? explode(',', $cartids) : '';

            $where = [];

            if ($userid) {

                $where['userid'] = $userid;
            }

            if ($cartids) {
                
                $where['cart.id'] = $cartid;
                // $where[] = ['id', 'in', $cartids];
            }

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }
            
            if($ispromptly){
               
                $product = $this->ProductModel->with(['type'])->find($cartids);

                $result[] = [
                    'total' => $product['price'],
                    'product' => $product,
                    'proid' => $product['id'],
                    'id' => $product['id'],
                    'nums'=> 1,
                    'price' => $product['price'],
                    'userid' => $userid
                ];
               
            } else {
                $result = $this->CartModel->withJoin('product')->where($where)->select();
            }
            // echo $this->CartModel->getlastsql();exit;

            if ($result === FALSE) {
                $this->error($this->CartModel->getError());
                exit;
            } else {
                $this->success('返回购物车记录成功', null, $result);
                exit;
            }
        }
    }

    // 添加购物车
    public function add()
    {
        if ($this->request->isPost()) {

            $proid = $this->request->param('proid', 0);

            $userid = $this->request->param('userid', 0);

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $productList = $this->ProductModel->find($proid);

            if (!$productList) {
                $this->error('商品不存在，请重新选择', '/product/product/index');
                exit;
            }

            if (!$productList['stock']) {

                $this->error('商品库存不足');
                exit;
            }

            $vip = isset($user) ? $user['vip'] : 0;

            if ($vip > 0) {
                $price = $this->VipModel->where(['proid' => $proid, 'level' => $vip])->value('price');
                $price = $price ? $price : $productList['price'];
            } else {
                $price = $productList['price'];
            }

            //先判断该产品是否有添加到购物车
            $cart = $this->CartModel->where(['proid' => $proid, 'userid' => $userid])->find();

            if ($cart) {

                $nums =  $cart['nums'] + 1;

                //总价  bcmul:精确乘法
                $total = bcmul($nums, $price);

                //组装数据
                $data = [
                    'id' => $cart['id'],
                    'userid' => $userid,
                    'proid' => $proid,
                    'nums' => $nums,
                    'price' => $price,
                    'total' => $total,
                ];

                // 引用验证器
                $validate = Validate::rule('app\common\validate\Cart');

                // 判断是否验证通过
                if (!$validate->check($data)) {
                    $this->error($validate->getError());
                    halt();
                }

                $result = $this->CartModel->update($data);

                if ($result === FALSE) {
                    $this->error($this->CartModel->getError());
                    exit;
                } else {
                    $this->success('添加购物车成功,是否跳转到购物车立即下单', '/product/cart/index');
                    exit;
                }
            } else {

                $data = [
                    'userid' => $userid,
                    'proid' => $proid,
                    'nums' => 1,
                    'price' => $price,
                    'total' => $price
                ];

                // 引用验证器
                $validate = Validate::rule('app\common\validate\Cart');

                // 判断是否验证通过
                if (!$validate->check($data)) {
                    $this->error($validate->getError());
                    halt();
                }

                $result = $this->CartModel->save($data);

                if ($result === FALSE) {
                    $this->error($this->CartModel->getError());
                    exit;
                } else {
                    $this->success('添加购物车成功,是否跳转到购物车立即下单', '/product/cart/index');
                    exit;
                }
            }
        }
    }

    // 编辑购物车
    public function  edit()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);
            $cartid = $this->request->param('cartid', 0);
            $nums = $this->request->param('nums', 0);

            $user = $this->UserModel->find($userid);
            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $price = $this->CartModel->find($cartid);

            $productList = $this->ProductModel->find($price['proid']);

            if (!$productList) {
                $this->error('商品不存在，请重新选择', '/product/product/index');
                exit;
            }

            if (!$productList['stock']) {

                $this->error('商品库存不足');
                exit;
            }

            $total =  bcmul($nums, $price['price']);

            //组装数据
            $data = [
                'id' => $cartid,
                'userid' => $userid,
                'nums' => $nums,
                'total' => $total,
            ];

            $result = $this->CartModel->update($data);

            if ($result === FALSE) {
                $this->error($this->CartModel->getError());
                exit;
            } else {
                $this->success('编辑购物车成功');
                exit;
            }
        }
    }

    // 删除购物车
    public function delete()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);
            $cartid = $this->request->param('cartid', 0);


            $user = $this->UserModel->find($userid);
            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $price = $this->CartModel->find($cartid);

            if (!$price) {
                $this->error('购物车记录不存在');
                exit;
            }

            $result = $this->CartModel->destroy($cartid, true);

            if ($result === FALSE) {
                $this->error($this->CartModel->getError());
                exit;
            } else {
                $this->success('删除购物车成功');
                exit;
            }
        }
    }
}
